
package com.ly.credit.service;


import com.ly.credit.dao.UserDao;
import com.ly.credit.entity.User;
import com.ly.credit.util.AdResult;
import com.ly.credit.util.EncodeUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Service("userService")
public class UserServiceImpl implements UserService {
	private static String Url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
	@Resource
	private UserDao userDao;
	@Resource
	private HttpServletRequest request;

	@Transactional
	public AdResult register(String name, String phone, String password, Integer code) throws Exception {

		AdResult result = new AdResult();
		User addUser = new User();
		addUser.setPassword(EncodeUtil.md5(password + "credit"));
		addUser.setPhone(phone);
		userDao.save(addUser);
		result.setStatus(1);
		result.setMsg("注册成功!");
		return result;

	}

	public AdResult login(String name, String phone, String password, Integer code) throws Exception {
		AdResult result = new AdResult();
		User user = new User();
		user.setPassword(EncodeUtil.md5(password + "credit"));
		user.setName(name);
		User findUser = userDao.login(user);
		if (findUser != null) {
			HttpSession session = request.getSession();
			session.setAttribute("user", findUser);
			result.setStatus(1);
			result.setMsg("登录成功!");
		} else {
			result.setStatus(0);
			result.setMsg("账号或密码错误!");
		}
		return result;
	}
	@Transactional
	public AdResult getKey() {
		AdResult result = new AdResult();
		try {
			HttpSession session = request.getSession();
			User user = (User)session.getAttribute("user");
			if(user==null){
				result.setStatus(2);
				result.setMsg("请先登录!");
				return result;
			}
			if(user.getAppkey()==null||"".equals(user.getAppkey())){
				String appkey = UUID.randomUUID().toString().replace("-", "").toLowerCase();
				user.setAppkey(appkey);
				userDao.getKey(user);
				User findUser = userDao.getUserById(user.getId());
				session.setAttribute("user", findUser);
				result.setStatus(1);
				result.setData(findUser);
				result.setMsg("获取成功!");
				return result;
			}else{
				result.setStatus(3);
				result.setMsg("已经申请appkey!");
				return result;
			}

		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(0);
			result.setMsg("获取失败!");
			return result;
		}
	}
	public AdResult getUserByPhoneAppkey (User user){
		AdResult result = new AdResult();
		User findUser = userDao.getUserByPhoneAppkey(user);
		if(findUser==null){
			result.setStatus(0);
			result.setMsg("账号或Appkey错误!");
		}else{
			result.setStatus(1);
			result.setMsg("获取成功!");
			result.setData(findUser);
		}
		return result;
	}
	public 	void updateUser (User user){
		userDao.updateUser(user);
	}
}